<?php

class site_zone_model extends CI_Model {

    const ZONE_TYPE_NORMAL = 1;
    const ZONE_TYPE_SLIDER = 2;

    protected $_instance = array(
        'table' => 'site_zone',
        'primaryKey' => 'id',
    );
    public $_data = null;

    public function get_zones() {
        $query = $this->db->get($this->_instance['table']);
        $list_zone = array();
        foreach ($query->result() as $row) {
            $list_zone[] = $row;
        }
        $query->free_result();
        return $list_zone;
    }

    public function count_total() {
        $query = $this->db->query('SELECT COUNT(id) AS count_total FROM ' . $this->_instance['table']);
        $row = $query->row();
        $query->free_result();
        if (empty($row) || !is_object($row)) {
            return 0;
        }
        return $row->count_total;
    }

    public function get_collection($start, $limit, $conds = null, $orders = null) {
        $query = 'SELECT * FROM ' . $this->_instance['table'];
        if (is_array($conds)) {
            $conds = implode(' AND ', $conds);
        }
        if (!empty($conds)) {
            $query .= ' WHERE ' . $conds;
        }
        if (!empty($orders)) {
            $query .= ' ORDER BY ' . $orders;
        }
        $query .= ' LIMIT ' . $start . ', ' . $limit;
        $query = $this->db->query($query);
        $list_zone = array();
        foreach ($query->result() as $row) {
            $list_zone[] = $row;
        }
        $query->free_result();
        return $list_zone;
    }

    public function get_parent_zones($eid) {
        $query = 'SELECT * FROM ' . $this->_instance['table'] . ' WHERE id <> ' . $eid;
        $query = $this->db->query($query);
        $list_zone = array();
        foreach ($query->result() as $row) {
            $list_zone[] = $row;
        }
        $query->free_result();
        return $list_zone;
    }

    public function add_zone($data) {
        $data = $this->auto_render($data);
        $id = false;
        if (empty($data['error'])) {
            $this->db->insert($this->_instance['table'], $data);
            $id = mysql_insert_id();
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $id;
    }

    public function update_zone($id, $data) {
        $data = $this->auto_render($data);
        $CI = & get_instance();
        if (empty($data['error'])) {
            //Update DB
            $this->db->where('id', $id);
            $this->db->update($this->_instance['table'], $data);
            //Update Memcache
            $CI->st_registry->deleteKey('site/zone_by_id/' . $id);
            $CI->st_registry->deleteKey('site/zone_by_code/' . $data['code']);
        } else {
            throw new Exception($data['error']);
            return false;
        }
        return $this;
    }

    public function load_by_id($id, $reload = false) {
        $CI =& get_instance();
        if (!GLOBAL_ENABLED_CACHE || $reload) {
            $query = $this->db->get_where($this->_instance['table'], array('id' => $id), 1, 0);
            $this->_data = $query->row();
            $this->_data = $this->render_after_load($this->_data);
            $CI->st_registry->setKey('site/zone_by_id/' . $id, $this->_data, GLOBAL_CACHE_DURATION);
            $query->free_result();
        } else {
            $this->_data = $CI->st_registry->getKey('site/zone_by_id/' . $id);
            if (!$this->_data) {
                return $this->load_by_id($id, true);
            }
        }
        return $this->_data;
    }

    public function load_by_code($code, $reload = false) {
        $CI =& get_instance();
        if (!GLOBAL_ENABLED_CACHE || $reload) {
            $query = $this->db->get_where($this->_instance['table'], array('code' => $code), 1, 0);
            $this->_data = $query->row();
            $this->_data = $this->render_after_load($this->_data);
            $CI->st_registry->setKey('site/zone_by_code/' . $code, $this->_data, GLOBAL_CACHE_DURATION);
            $query->free_result();
        } else {
            $this->_data = $CI->st_registry->getKey('site/zone_by_code/' . $code);
            if (!$this->_data) {
                return $this->load_by_code($code, true);
            }
        }
        return $this->_data;
    }

    // Check Exists Product By Field, Value
    public static function exists_zone($field, $value, $reload = false) {
        $CI =& get_instance();
        if (!GLOBAL_ENABLED_CACHE || $reload) {
            $query = $CI->db->get_where($CI->_instance['table'], array($field => $value), 1, 0);
            $data = $query->row();
            if (!empty($data) && intval($data->id) > 0) {
                $query->free_result();
                $CI->st_registry->setKey('site/zone_by_' . $field . '/' . $value, $data, GLOBAL_CACHE_DURATION);
                return $data;
            }
        } else {
            $data = $CI->st_registry->getKey('site/zone_by_' . $field . '/' . $value);
            if (empty($data)) {
                return $CI->exists_zone($field, $value, true);
            }
        }
        return false;
    }

    public function get_data($data, $field) {
        if (is_string($data) && strstr($data, ':')) {
            $data = unserialize($data);
        }
        if (!is_array($data)) {
            return false;
        }
        if (isset($data[$field])) {
            return $data[$field];
        }
        return false;
    }

    public function delete_zone($id) {
        // Delete From DB
        $this->db->delete($this->_instance['table'], array('id' => $id));
        // Delete From Memcache
        $CI =& get_instance();
        $CI->st_registry->deleteKey('site/zone_by_id/' . $id);
        return $this;
    }

    private function auto_render($data) {
        if (empty($data['code'])) {
            $data['code'] = renderToAlias($data['heading']);
        } else {
            $data['code'] = renderToAlias($data['code']);
        }
        return $data;
    }

    private function render_after_load($data) {
        if (!empty($data->width)) {
            $data->width = str_replace('px', '', $data->width);
        }
        if (!empty($data->height)) {
            $data->height = str_replace('px', '', $data->height);
        }
        return $data;
    }

    public static function get_edit_url($id = null) {
        if (empty($id)) {
            return site_url('admin/site/zone/edit/', true);
        }
        return site_url('admin/site/zone/edit/id/' . $id, true);
    }

    public function get_type_label($type) {
        $label = 'Thông thường';
        switch ($type) {
            case site_zone_model::ZONE_TYPE_NORMAL:
                $label = 'Thông thường';
                break;
            case site_zone_model::ZONE_TYPE_SLIDER:
                $label = 'Slider';
                break;
            default:
                $label = 'Thông thường';
                break;
        }
        return $label;
    }

    public function get_types() {
        $types = array();
        $types[site_zone_model::ZONE_TYPE_NORMAL] = $this->get_type_label(site_zone_model::ZONE_TYPE_NORMAL);
        $types[site_zone_model::ZONE_TYPE_SLIDER] = $this->get_type_label(site_zone_model::ZONE_TYPE_SLIDER);
        return $types;
    }

    public function get_item_collection($id) {
        $item_model = new site_banner_model();
        $items = $item_model->get_collection(0, 0, 'zone_id = ' . $id . ' AND is_visible = 1', 'zone_id ASC, sort_order ASC');
        return $items;
    }

    public function render_zone($code) {
        $data['zone'] = $this->load_by_code($code, true);
        if (empty($data['zone']) || $data['zone']->hidden == 1) {
            return '';
        }
        $data['items'] = $this->get_item_collection($data['zone']->id);
        if (empty($data['items'])) {
            return '';
        }
        $CI = & get_instance();
        $output = $CI->load->view('page/layouts/widgets/zone', $data, true);
        return $output;
    }
}

?>